package com.zcily.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcily.demo.entity.dto.Result;
import com.zcily.demo.entity.po.User;
import com.zcily.demo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@Slf4j
@Api(tags = "用户信息")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    @ApiOperation(value = "用户列表")
    public String list(Model model) {
        Page<User> page = Page.of(0, 10, true);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(User::getUsername, "admin");
        Page<User> data = userService.page(page, wrapper);
        model.addAttribute("users", data.getRecords());
        return "user-list";
    }

    @GetMapping("/detail/{id}")
    @ApiOperation(value = "用户详情")
    public String detail(@PathVariable("id") Integer userId, Model model) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId, userId);
        User user = userService.getOne(wrapper);
        model.addAttribute("user", user);
        return "user-detail";
    }

    @PostMapping("/set/avatar")
    @ApiOperation(value = "用户详情")
    @ResponseBody
    public Result<?> setAvatar(@RequestBody User user) {
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(User::getAvatar, user.getAvatar());
        wrapper.eq(User::getId, user.getId());
        userService.update(null, wrapper);
        return Result.ok();
    }

    @GetMapping("/listByOrg")
    @ApiOperation(value = "根据机构查询用户列表")
    @ResponseBody
    public Result<List<User>> listByOrg(@RequestParam("orgId") Integer orgId) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(User::getOrgId, orgId);
        List<User> data = userService.list(wrapper);
        return Result.ok(data);
    }
}
